const { createApp } = Vue

createApp({
    data() {
        return {
            loading: false,
            profile: {
                name: '',
                title: '',
                qualification: '',
                experience: '',
                avatar: '',
                fields: [],
                bio: '',
                expertise: '',
                phone: '',
                email: ''
            },
            availableFields: [
                { id: 1, name: '个人成长', description: '自我认知、生涯规划、人际关系等' },
                { id: 2, name: '情绪管理', description: '焦虑、抑郁、压力管理等' },
                { id: 3, name: '婚恋关系', description: '恋爱、婚姻、家庭关系等' },
                { id: 4, name: '职场压力', description: '工作适应、职业倦怠、团队沟通等' }
            ]
        }
    },
    computed: {
        currentDate() {
            const now = new Date()
            const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' }
            return now.toLocaleDateString('zh-CN', options)
        }
    },
    methods: {
        // 获取个人信息
        async fetchProfile() {
            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '/login.html';
                    return;
                }

                const response = await fetch('/api/therapist/profile', {
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json'
                    }
                });

                // 检查响应状态
                if (response.status === 401) {
                    console.log('Token已失效，需要重新登录');
                    localStorage.removeItem('token'); // 清除失效的token
                    window.location.href = '/login.html';
                    return;
                }

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                if (data.code === "200") {
                    // 更新数据
                    this.profile = {
                        name: data.data.name || '',
                        title: data.data.title || '',
                        qualification: data.data.qualification || '',
                        experience: data.data.experience || '',
                        fields: data.data.fields || [],
                        bio: data.data.bio || '',
                        expertise: data.data.expertise || '',
                        phone: data.data.phone || '',
                        email: data.data.email || ''
                    };
                } else if (data.code === "401") {
                    console.log('Token验证失败');
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                } else {
                    console.error('获取个人信息失败:', data.message);
                    alert(data.message || '获取个人信息失败');
                }
            } catch (error) {
                console.error('获取个人信息出错:', error);
                if (error.response?.status === 401) {
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                } else {
                    alert('获取个人信息失败，请稍后重试');
                }
            }
        },

        toggleField(fieldName) {
            const index = this.profile.fields.indexOf(fieldName);
            if (index > -1) {
                this.profile.fields.splice(index, 1);
            } else if (this.profile.fields.length < 3) {
                this.profile.fields.push(fieldName);
            } else {
                alert('最多只能选择3个咨询领域');
            }
        },

        isFieldSelected(fieldName) {
            return this.profile.fields.includes(fieldName);
        },

        goToPage(page) {
            switch (page) {
                case 'index':
                    window.location.href = 'index.html';
                    break;
                case 'schedule':
                    window.location.href = 'schedule.html';
                    break;
                case 'records':
                    window.location.href = 'records.html';
                    break;
                case 'profile':
                    window.location.href = 'profile.html';
                    break;
            }
        },

        validateForm() {
            // 姓名验证
            if (!this.profile.name) {
                alert('请输入姓名');
                return false;
            }
            if (this.profile.name.length < 2 || this.profile.name.length > 20) {
                alert('姓名长度应为2-20个字符');
                return false;
            }

            // 职称验证
            if (!this.profile.title) {
                alert('请输入职称');
                return false;
            }
            if (this.profile.title.length > 50) {
                alert('职称长度不能超过50个字符');
                return false;
            }

            // 资质验证
            if (!this.profile.qualification) {
                alert('请输入专业资质');
                return false;
            }

            // 从业经验验证
            if (!this.profile.experience) {
                alert('请输入从业经验');
                return false;
            }

            // 擅长领域验证
            if (!this.profile.fields || this.profile.fields.length === 0) {
                alert('请至少选择一个擅长领域');
                return false;
            }

            // 个人简介验证
            if (!this.profile.bio) {
                alert('请填写个人简介');
                return false;
            }
            if (this.profile.bio.length < 5 || this.profile.bio.length > 200) {
                alert('个人简介长度应在50-1000字之间');
                return false;
            }

            // 邮箱验证
            if (this.profile.email) {
                const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
                if (!emailRegex.test(this.profile.email)) {
                    alert('请输入正确的邮箱格式');
                    return false;
                }
            }

            return true;
        },

        async saveProfile() {
            if (!this.validateForm()) {
                return;
            }

            this.loading = true;
            try {
                console.log('开始保存个人信息:', this.profile);

                const token = localStorage.getItem('token');
                const response = await fetch('/api/therapist/profile', {
                    method: 'PUT',
                    headers: {
                        'Authorization': token,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: this.profile.name,
                        title: this.profile.title,
                        qualification: this.profile.qualification,
                        experience: this.profile.experience,
                        fields: this.profile.fields,
                        bio: this.profile.bio,
                        expertise: this.profile.expertise,
                        phone: this.profile.phone,
                        email: this.profile.email
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log('保存响应:', data);

                if (data.code === "200") {
                    alert('保存成功');
                    // 重新获取最新数据
                    await this.fetchProfile();
                } else {
                    console.error('保存失败:', data.message);
                    alert(data.message || '保存失败');
                }
            } catch (error) {
                console.error('保存出错:', error);
                if (error.response?.status === 401) {
                    window.location.href = '/login.html';
                } else {
                    alert('保存失败，请稍后重试');
                }
            } finally {
                this.loading = false;
            }
        }
    },
    created() {
        // 页面创建时获取个人信息
        this.fetchProfile();
    }
}).mount('#app') 